package main

import (
	"fmt"
	"net/http"
	"os"
	"strings"
)

const (
	IMG_DIR_TRUE  string = "./img/"
	IMG_DIR_FALSE string = "/images/"
	HTTP_PORT     string = ":9001"
)

type Router struct {
	Route map[string]map[string]http.HandlerFunc
}

func (t *Router) HandleFunc(method, path string, f http.HandlerFunc) {
	method = strings.ToUpper(method) //请求方式转为大写 get post...
	if t.Route == nil {
		t.Route = make(map[string]map[string]http.HandlerFunc)
	}
	if t.Route[method] == nil {
		t.Route[method] = make(map[string]http.HandlerFunc)
	}
	t.Route[method][path] = f
}

func (t *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// 正常路由
	if f, ok := t.Route[r.Method][r.URL.Path]; ok {
		f(w, r)
		//静态文件路由
	} else if strings.HasPrefix(r.URL.String(), IMG_DIR_FALSE) {
		//		staticFile := http.StripPrefix(StaticHttpPath, http.FileServer(http.Dir(StaticHttpPath)))
		//		staticFile.ServeHTTP(w, r)
		Images(w, r)
	} else {
		fmt.Fprintln(w, "404")
	}
}

func main() {
	var route = &Router{}
	route.HandleFunc("GET", "/", Index)
	route.HandleFunc("GET", "/login", Login)
	route.HandleFunc("GET", IMG_DIR_FALSE, Images)
	err := http.ListenAndServe(HTTP_PORT, route)
	if err != nil {
		fmt.Println(err)
	}
}

func Index(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "Index")
}

func Login(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "Login")
}

func Images(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path[len(IMG_DIR_FALSE):] == "" {
		fmt.Fprintln(w, "错路的路径")
		return
	}
	file := IMG_DIR_TRUE + r.URL.Path[len(IMG_DIR_FALSE):]
	f, err := os.Open(file)
	if err != nil && os.IsNotExist(err) {
		file = IMG_DIR_TRUE + "/1.jpg"
	}
	defer f.Close()
	http.ServeFile(w, r, file)
	return
}
